package cc.geguol.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 作者：13687
 * 日期：2017/5/29
 * 项目：Socket
 * 描述：测试
 * 客户端 向服务端发送：你好
 * 服务端 接收到后发送：收到，你也好
 * 客户端 接受呗
 * 可能存在的问题：
 * 1. 数据刷新 flush 没有
 * 2. 数据读取readLine() 卡在没有\r\n 回车
 *
 */
public class SocketServer {
	public static void main(String[] args) throws UnknownHostException {
		try {
			//  1. 先启动服务器
			ServerSocket serverSocket = new ServerSocket(5557);
			new Server(serverSocket).start();
			Thread.sleep(500);// 需要先启动服务器
			new Client(new Socket(InetAddress.getLocalHost().getHostAddress(),5557)).start();
			// 3. 接收
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Server extends Thread{
	public Server(ServerSocket socket) {
		this.socket = socket;
	}

	private ServerSocket socket;

	@Override
	public void run() {
		while (true){
			try {
				Socket cs = socket.accept();//阻塞
				BufferedReader reader = new BufferedReader(new InputStreamReader(cs.getInputStream()));
				String message = reader.readLine();//阻塞
				System.out.println("矜持住:"+message);
				Thread.sleep(500);
				OutputStream out = cs.getOutputStream();
				out.write("我也爱你哟\r\n".getBytes());//指定回车换行 通知结束
				out.flush();
//				cs.shutdownOutput(); 这个也是通知结束
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}
}

class Client extends Thread{
	public Client(Socket socket) {
		this.socket = socket;
	}

	Socket socket;

	@Override
	public void run() {
		try {
			OutputStream out = socket.getOutputStream();
			out.write("woaidaya\r\n".getBytes());
			InputStream in = socket.getInputStream();

			byte[] buff=new byte[1024];
			int len = in.read(buff);// 这里是阻塞方式
//
			System.out.println(new String(buff,0,len));
			socket.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}